<template>
  <div class="window-controls" v-if="isElectron">
    <div class="controls-group">
      <!-- 最小化按钮 -->
      <el-tooltip content="最小化" placement="bottom">
        <button 
          class="control-btn minimize-btn"
          @click="minimize"
          :disabled="loading"
        >
          <el-icon><Minus /></el-icon>
        </button>
      </el-tooltip>

      <!-- 最大化/还原按钮 -->
      <el-tooltip :content="isMaximized ? '还原' : '最大化'" placement="bottom">
        <button 
          class="control-btn maximize-btn"
          @click="toggleMaximize"
          :disabled="loading"
        >
          <el-icon>
            <CopyDocument v-if="isMaximized" />
            <FullScreen v-else />
          </el-icon>
        </button>
      </el-tooltip>

      <!-- 关闭按钮 -->
      <el-tooltip content="关闭" placement="bottom">
        <button 
          class="control-btn close-btn"
          @click="close"
          :disabled="loading"
        >
          <el-icon><Close /></el-icon>
        </button>
      </el-tooltip>
    </div>

    <!-- 扩展控制 -->
    <div class="extended-controls" v-if="showExtended">
      <!-- 置顶按钮 -->
      <el-tooltip :content="isAlwaysOnTop ? '取消置顶' : '窗口置顶'" placement="bottom">
        <button 
          class="control-btn pin-btn"
          :class="{ active: isAlwaysOnTop }"
          @click="toggleAlwaysOnTop"
          :disabled="loading"
        >
          <el-icon><Position /></el-icon>
        </button>
      </el-tooltip>

      <!-- 全屏按钮 -->
      <el-tooltip :content="isFullScreen ? '退出全屏' : '全屏'" placement="bottom">
        <button 
          class="control-btn fullscreen-btn"
          :class="{ active: isFullScreen }"
          @click="toggleFullScreen"
          :disabled="loading"
        >
          <el-icon><Monitor /></el-icon>
        </button>
      </el-tooltip>

      <!-- 开发者工具 -->
      <el-tooltip content="开发者工具" placement="bottom" v-if="isDev">
        <button 
          class="control-btn devtools-btn"
          @click="toggleDevTools"
          :disabled="loading"
        >
          <el-icon><Tools /></el-icon>
        </button>
      </el-tooltip>
    </div>

    <!-- 窗口信息显示 -->
    <div class="window-info" v-if="showInfo">
      <div class="info-item">
        <span class="label">窗口状态:</span>
        <el-tag size="small" :type="getWindowStatusType()">
          {{ getWindowStatusText() }}
        </el-tag>
      </div>
      <div class="info-item" v-if="windowBounds">
        <span class="label">尺寸:</span>
        <span class="value">{{ windowBounds.width }} × {{ windowBounds.height }}</span>
      </div>
      <div class="info-item" v-if="windowBounds">
        <span class="label">位置:</span>
        <span class="value">{{ windowBounds.x }}, {{ windowBounds.y }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Minus, Close, FullScreen, CopyDocument, Position, 
  Monitor, Tools 
} from '@element-plus/icons-vue'

// Props
interface Props {
  showExtended?: boolean
  showInfo?: boolean
  confirmClose?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showExtended: false,
  showInfo: false,
  confirmClose: false
})

// Emits
const emit = defineEmits<{
  beforeMinimize: []
  beforeMaximize: []
  beforeClose: []
  windowStateChanged: [state: string]
}>()

// 状态管理
const isElectron = !!(window as any).electronAPI
const loading = ref(false)
const isMaximized = ref(false)
const isFullScreen = ref(false)
const isAlwaysOnTop = ref(false)
const windowBounds = ref<any>(null)

// 环境检测
const isDev = process.env.NODE_ENV === 'development'

// 获取Electron API
const getElectronAPI = () => {
  if (!isElectron) {
    throw new Error('Electron API不可用')
  }
  return (window as any).electronAPI
}

// 最小化窗口
const minimize = async () => {
  if (loading.value) return
  
  loading.value = true
  emit('beforeMinimize')
  
  try {
    const electronAPI = getElectronAPI()
    await electronAPI.app.minimize()
    emit('windowStateChanged', 'minimized')
  } catch (error) {
    console.error('最小化失败:', error)
    ElMessage.error('最小化失败')
  } finally {
    loading.value = false
  }
}

// 切换最大化状态
const toggleMaximize = async () => {
  if (loading.value) return
  
  loading.value = true
  emit('beforeMaximize')
  
  try {
    const electronAPI = getElectronAPI()
    await electronAPI.app.maximize()
    
    // 更新状态（这里应该通过事件监听获取实际状态）
    isMaximized.value = !isMaximized.value
    emit('windowStateChanged', isMaximized.value ? 'maximized' : 'normal')
  } catch (error) {
    console.error('最大化切换失败:', error)
    ElMessage.error('窗口操作失败')
  } finally {
    loading.value = false
  }
}

// 关闭窗口
const close = async () => {
  if (loading.value) return
  
  if (props.confirmClose) {
    const { ElMessageBox } = await import('element-plus')
    try {
      await ElMessageBox.confirm(
        '确定要关闭应用吗？',
        '确认关闭',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    } catch {
      return // 用户取消
    }
  }
  
  loading.value = true
  emit('beforeClose')
  
  try {
    const electronAPI = getElectronAPI()
    await electronAPI.app.close()
  } catch (error) {
    console.error('关闭失败:', error)
    ElMessage.error('关闭失败')
  } finally {
    loading.value = false
  }
}

// 切换置顶状态
const toggleAlwaysOnTop = async () => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    // 这里需要在主进程中实现setAlwaysOnTop方法
    const electronAPI = getElectronAPI()
    if (electronAPI.app.setAlwaysOnTop) {
      await electronAPI.app.setAlwaysOnTop(!isAlwaysOnTop.value)
      isAlwaysOnTop.value = !isAlwaysOnTop.value
      
      ElMessage.success(isAlwaysOnTop.value ? '窗口已置顶' : '已取消置顶')
      emit('windowStateChanged', isAlwaysOnTop.value ? 'alwaysOnTop' : 'normal')
    } else {
      ElMessage.warning('置顶功能暂不可用')
    }
  } catch (error) {
    console.error('置顶切换失败:', error)
    ElMessage.error('置顶操作失败')
  } finally {
    loading.value = false
  }
}

// 切换全屏状态
const toggleFullScreen = async () => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    // 这里需要在主进程中实现setFullScreen方法
    const electronAPI = getElectronAPI()
    if (electronAPI.app.setFullScreen) {
      await electronAPI.app.setFullScreen(!isFullScreen.value)
      isFullScreen.value = !isFullScreen.value
      
      ElMessage.success(isFullScreen.value ? '已进入全屏' : '已退出全屏')
      emit('windowStateChanged', isFullScreen.value ? 'fullscreen' : 'normal')
    } else {
      ElMessage.warning('全屏功能暂不可用')
    }
  } catch (error) {
    console.error('全屏切换失败:', error)
    ElMessage.error('全屏操作失败')
  } finally {
    loading.value = false
  }
}

// 切换开发者工具
const toggleDevTools = async () => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    const electronAPI = getElectronAPI()
    if (electronAPI.devTools) {
      await electronAPI.devTools.open()
      ElMessage.success('开发者工具已打开')
    } else {
      ElMessage.warning('开发者工具不可用')
    }
  } catch (error) {
    console.error('开发者工具打开失败:', error)
    ElMessage.error('开发者工具操作失败')
  } finally {
    loading.value = false
  }
}

// 获取窗口状态类型
const getWindowStatusType = () => {
  if (isFullScreen.value) return 'danger'
  if (isMaximized.value) return 'warning'
  if (isAlwaysOnTop.value) return 'success'
  return 'info'
}

// 获取窗口状态文本
const getWindowStatusText = () => {
  if (isFullScreen.value) return '全屏'
  if (isMaximized.value) return '最大化'
  if (isAlwaysOnTop.value) return '置顶'
  return '正常'
}

// 更新窗口信息
const updateWindowInfo = async () => {
  if (!isElectron) return
  
  try {
    const electronAPI = getElectronAPI()
    if (electronAPI.app.getWindowBounds) {
      windowBounds.value = await electronAPI.app.getWindowBounds()
    }
  } catch (error) {
    console.error('获取窗口信息失败:', error)
  }
}

// 监听窗口状态变化
const setupWindowListeners = () => {
  if (!isElectron) return
  
  // 这里应该监听主进程发送的窗口状态变化事件
  // 例如：electronAPI.on('window-state-changed', handleWindowStateChange)
}

// 组件挂载时初始化
onMounted(() => {
  if (isElectron) {
    setupWindowListeners()
    updateWindowInfo()
    
    // 定期更新窗口信息
    const interval = setInterval(updateWindowInfo, 5000)
    
    onUnmounted(() => {
      clearInterval(interval)
    })
  }
})
</script>

<style scoped>
.window-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  user-select: none;
}

.controls-group {
  display: flex;
  align-items: center;
  gap: 4px;
}

.extended-controls {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-left: 8px;
  padding-left: 8px;
  border-left: 1px solid #EBEEF5;
}

.control-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: #606266;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}

.control-btn:hover {
  background: #F5F7FA;
  color: #409EFF;
}

.control-btn:active {
  background: #E6F7FF;
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.close-btn:hover {
  background: #F56C6C;
  color: white;
}

.control-btn.active {
  background: #409EFF;
  color: white;
}

.control-btn.active:hover {
  background: #337ECC;
}

.window-info {
  margin-left: 16px;
  padding-left: 16px;
  border-left: 1px solid #EBEEF5;
  font-size: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #909399;
  font-weight: 500;
}

.value {
  color: #606266;
  font-family: 'Courier New', monospace;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .window-controls {
    gap: 4px;
  }
  
  .control-btn {
    width: 28px;
    height: 28px;
    font-size: 12px;
  }
  
  .window-info {
    display: none;
  }
}
</style>
